package com.example.gitzuoye3;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import java.util.ArrayList;
import java.util.List;

/**
 * 个人中心Fragment，显示用户信息和收藏电影列表
 * 实现OnDetailButtonClickListener接口以处理电影详情点击事件
 */
public class gerenxinxi extends Fragment implements shipeiqi.OnDetailButtonClickListener {

    // UI组件
    private TextView usernameView;          // 显示用户名的TextView
    private TextView introductionView;      // 显示个人介绍的TextView
    private Button editIntroBtn;           // 编辑个人介绍的按钮
    private Button tuichuButton;           // 退出登录按钮
    private ListView favoritesListView;    // 收藏电影列表

    // 适配器和数据
    private shipeiqi adapter;              // 电影列表适配器
    private List<xiangxi.DianyingItem> favoriteMovies = new ArrayList<>(); // 收藏电影列表

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        // 1. 加载布局文件
        View view = inflater.inflate(R.layout.geren, container, false);

        // 2. 初始化UI组件
        usernameView = view.findViewById(R.id.username);
        introductionView = view.findViewById(R.id.profile_introduction);
        editIntroBtn = view.findViewById(R.id.edit_introduction_btn);
        tuichuButton = view.findViewById(R.id.tuichu);
        favoritesListView = view.findViewById(R.id.favorites_list);

        // 3. 从SharedPreferences加载用户名并显示
        SharedPreferences sp = getActivity().getSharedPreferences("user_profile", Context.MODE_PRIVATE);
        String username = sp.getString("username", "用户");
        usernameView.setText(username);

        // 4. 加载个人介绍和收藏电影
        loadIntroduction();
        loadFavoriteMovies();

        // 5. 初始化适配器并设置到ListView
        adapter = new shipeiqi(getActivity(), favoriteMovies, this);
        adapter.setFavoriteChangeListener(new shipeiqi.OnFavoriteChangeListener() {
            @Override
            public void onFavoriteChanged() {
                // 当收藏状态变化时刷新列表
                loadFavoriteMovies();
                adapter.notifyDataSetChanged();
            }
        });
        favoritesListView.setAdapter(adapter);

        // 6. 设置编辑按钮点击事件
        editIntroBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showEditIntroductionDialog();
            }
        });

        // 7. 设置退出登录按钮点击事件
        tuichuButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                logoutUser();
            }
        });

        return view;
    }

    /**
     * 从SharedPreferences加载个人介绍
     */
    private void loadIntroduction() {
        SharedPreferences sp = requireActivity().getSharedPreferences("user_profile", Context.MODE_PRIVATE);
        String introduction = sp.getString("introduction", "还没有个人介绍...");
        introductionView.setText(introduction);
    }

    /**
     * 加载收藏的电影列表
     */
    private void loadFavoriteMovies() {
        SharedPreferences favoritesPrefs = requireActivity().getSharedPreferences("favorites", Context.MODE_PRIVATE);
        List<xiangxi.DianyingItem> allMovies = getAllMovies();

        favoriteMovies.clear();

        // 遍历所有电影，检查是否被收藏
        for (xiangxi.DianyingItem movie : allMovies) {
            if (favoritesPrefs.getBoolean(String.valueOf(movie.getId()), false)) {
                favoriteMovies.add(movie);
            }
        }

        if (favoriteMovies.isEmpty()) {
            Toast.makeText(getActivity(), "您还没有收藏任何电影", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 获取所有电影列表
     * @return 包含所有电影信息的列表
     */
    private List<xiangxi.DianyingItem> getAllMovies() {
        List<xiangxi.DianyingItem> allMovies = new ArrayList<>();
        allMovies.add(new xiangxi.DianyingItem(1, "大话西游", "导演：刘镇伟\n主演：周星驰、朱茵、吴孟达、蓝洁瑛、莫文蔚等。", "dhxy"));
        allMovies.add(new xiangxi.DianyingItem(2, "哈利波特与凤凰社", "导演：大卫·叶斯\n主演：丹尼尔·雷德克里夫、爱玛·沃森、鲁伯特·格林特等。 ", "fhs"));
        allMovies.add(new xiangxi.DianyingItem(3, "千与千寻", "导演：宫崎骏\n主演：柊柊柊柊柊柊柊柊瑠瑠瑠瑠瑠瑠瑠瑠美、入野自由、夏木麻里等。", "qyqx"));
        allMovies.add(new xiangxi.DianyingItem(4, "热烈", "导演：大鹏\n主演：黄渤、王一博、刘敏涛、岳云鹏、小沈阳等。", "rl"));
        allMovies.add(new xiangxi.DianyingItem(5, "唐人街探案3", "导演：陈思诚\n主演：王宝强、刘昊然、长泽雅美，妻夫木聪，三浦友和，肖阳，邱泽，陈哲远，张子枫，程潇，尚语贤等。\"", "tt3"));
        allMovies.add(new xiangxi.DianyingItem(6, "我爱你", "导演：韩延\n主演：倪大红、惠英红", "wan"));
        allMovies.add(new xiangxi.DianyingItem(7, "一出好戏", "导演：黄渤\n主演：黄渤、王宝强、舒淇、张艺兴、于和伟、王迅等。", "ychx"));
        allMovies.add(new xiangxi.DianyingItem(8, "哪吒之魔童闹海", "导演：饺子\n主要配音：吕艳婷、囧囧囧囧囧囧囧囧森瑟夫、瀚墨、陈浩、绿绮等。", "nz"));

        return allMovies;
    }

    @Override
    public void onResume() {
        super.onResume();
        // 每次返回页面时刷新收藏列表
        loadFavoriteMovies();
        adapter.notifyDataSetChanged();
    }

    /**
     * 显示编辑个人介绍的对话框
     */
    private void showEditIntroductionDialog() {
        android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(getActivity());
        View dialogView = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_edit_intro, null);
        builder.setView(dialogView);

        final android.widget.EditText introEditText = dialogView.findViewById(R.id.intro_edit_text);
        Button saveBtn = dialogView.findViewById(R.id.save_intro_btn);

        // 加载当前介绍内容
        SharedPreferences sp = requireActivity().getSharedPreferences("user_profile", Context.MODE_PRIVATE);
        String currentIntro = sp.getString("introduction", "");
        introEditText.setText(currentIntro);

        final android.app.AlertDialog dialog = builder.create();
        dialog.show();

        saveBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String newIntro = introEditText.getText().toString().trim();

                if (newIntro.isEmpty()) {
                    Toast.makeText(getActivity(), "个人介绍不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }

                // 保存到SharedPreferences
                SharedPreferences.Editor editor = sp.edit();
                editor.putString("introduction", newIntro);
                editor.apply();

                // 更新UI
                introductionView.setText(newIntro);
                dialog.dismiss();
                Toast.makeText(getActivity(), "个人介绍已更新", Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 处理用户退出登录逻辑
     */
    private void logoutUser() {
        // 清除登录信息
        SharedPreferences loginPrefs = requireActivity().getSharedPreferences("login_info", Context.MODE_PRIVATE);
        loginPrefs.edit().clear().apply();

        // 清除个人资料（可选）
        SharedPreferences profilePrefs = requireActivity().getSharedPreferences("user_profile", Context.MODE_PRIVATE);
        profilePrefs.edit().clear().apply();

        // 创建跳转到登录页面的Intent
        Intent intent = new Intent(requireActivity(), MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
        requireActivity().finish();
    }

    /**
     * 实现OnDetailButtonClickListener接口方法
     * 处理电影详情按钮点击事件
     */
    @Override
    public void onDetailButtonClick(xiangxi.DianyingItem item) {
        try {
            getParentFragmentManager().beginTransaction()
                    .replace(R.id.dianying_list, dianyingxinxi.newInstance(item))
                    .addToBackStack(null)
                    .commit();
        } catch (Exception e) {
            Toast.makeText(getActivity(), "打开详情失败", Toast.LENGTH_SHORT).show();
        }
    }
}